package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.检查参数  分页查询页码检查
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.封装查询语句
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //文章标题模糊查询
        queryWrapper.eq(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle,dto.getKeyword());
        //频道Id查询
        queryWrapper.eq(dto.getChannelId()!=null, WmNews::getChannelId,dto.getChannelId());
        //文章状态信息查询
        queryWrapper.eq(dto.getStatus()!=null, WmNews::getStatus,dto.getStatus());
        //根据开始时间，结束时间的时间区间查询
        queryWrapper.gt(dto.getBeginPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());
        queryWrapper.lt(dto.getEndPubDate()!=null, WmNews::getPublishTime,dto.getEndPubDate());
        //根据登录用户Id查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //按照创建时间降序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        //3.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> resultPage = page(page, queryWrapper);
        //4.封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(),resultPage.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1.检查参数
        if (wmNewsDto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        //如果文章属性是自动则需要设置为null
        if (wmNews.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        String images = imageListToStr(wmNewsDto.getImages(), webSite);
        wmNews.setImages(images);
        saveWmnews(wmNews);
        //如果是待审核状态，则需要保存内容图片封面图片和素材图片之间的关联关系
        //status 0草稿 1待审核
        if (wmNewsDto.getStatus().intValue()==0) {
            return ResponseResult.okResult();
        }
        //3.1抽取内容中涉及的图片
        List<Map> content = JSON.parseArray(wmNews.getContent(), Map.class);
        List<String> materials = parseContentImages(content);
        //3.2保存内容与图片之间的关联关系
        if (CollectionUtils.isNotEmpty(materials)) {
            saveRelativeInfo(materials, wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //3.3保存封面图片与素材之间的关联关系
        saveRelativeInfoForCover(wmNewsDto,materials, wmNews);

        Map map = new HashMap();
        map.put("newsID",wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        log.info("文章自动审核消息 已成功发送 文章id： {}",wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);
        if(wmNews.getArticleId()!=null){
            Map<String,Object> mesMap = new HashMap<>();
            mesMap.put("enable",dto.getEnable());
            mesMap.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));
        }

        Map map = new HashMap();
        map.put("articleId",wmNews.getArticleId());
        if(dto.getEnable().intValue() == 0){
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,JSON.toJSONString(map));
        }else {
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 查询需要发布的文章id列表  wm_news   4  8    publishTime < = now()
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8)
                .select(WmNews::getId));

        List<Integer> idList = list.stream().map(WmNews::getId)
                .collect(Collectors.toList());
        return idList;
    }
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();
        Integer currentPage = dto.getPage();
        dto.setPage((currentPage-1)*dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        long count = wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult = new PageResponseResult(currentPage, dto.getSize(), count,listAndPage);
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }
    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        WmUser wmUser =null;
        if (wmNews.getUserId()==null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        if (status==null||dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, List<String> materials, WmNews wmNews) {
        //前端用户选择的图片
        List<String> images = wmNewsDto.getImages();
        //封面自动生成
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {

            if (CollectionUtils.isEmpty(materials)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images=null;
            } else if (materials.size()<= 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (CollectionUtils.isNotEmpty(images)){
                wmNews.setImages(imageListToStr(images,webSite));

            }
            updateById(wmNews);
        }
        if (CollectionUtils.isNotEmpty(images)){
            //如果是用户手动上传的图片那么需要处理一下路径
            images = images.stream().map(url->url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        //1.根据url和用户ID查询所有的素材信息
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materialUrls)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"引用的素材不存在");
        }
        //2.将url作为key，用户ID作为value存入map集合
        Map<String, Integer> collect = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getUserId));
        ArrayList<Integer> list = new ArrayList<>();
        materialUrls.forEach(
                url->{
                    if (!collect.containsKey(url)) {
                        CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"引用的素材不存在");
                    }
                    list.add(collect.get(url));
                }
        );
        //批量插入
        wmNewsMaterialMapper.saveRelations(list,newsId,type);
    }

    //
    private List<String> parseContentImages(List<Map> content) {
        // 遍历文章内容   将所有 type为image的 value获取出来  去除前缀路径
        List<String> list = content.stream().filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                .map(map -> (String) map.get("value"))//获取map中value的值
                .map(url -> url.replaceAll(webSite, ""))//去掉前缀
                .collect(Collectors.toList());
        return list;
    }

    private void saveWmnews(WmNews wmNews) {
        //根据有无文章的Id判断是修改还是删除
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId()==null) {
            save(wmNews);
        }else {
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                                                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
            updateById(wmNews);
        }
    }

    /**
     * 去除图片路径的前缀，并拼接成字符串，中间以 逗号 分割
     * @param images
     * @param webSite
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
        String str = images.stream().map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));
        return str;
    }
}
